<template>
  <div class="point_product">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="68px"
      class="globalSerchFormStyle"
    >
      <el-row>
        <el-col :span="6">
          <el-form-item label="商品名称" prop="waresName">
            <el-input
              v-model="queryParams.waresName"
              placeholder="请输入商品名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
              style="width: 190px"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row class="global_el_rowStyle" :gutter="10">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
          plain
          >重置</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button plain icon="el-icon-plus" size="mini" @click="handleAdd"
          >新增</el-button
        >
      </el-col>
    </el-row>

    <el-table :data="waresList" stripe>
      <af-table-column
        label="油站"
        align="left"
        prop="stationName"
        v-if="userLevel == 1"
      />
      <af-table-column label="商品id" align="left" prop="id" v-if="false" />
      <af-table-column
        label="商品类别"
        align="left"
        prop="waresType"
        v-if="false"
      />
      <af-table-column label="商品名称" align="left" prop="waresName" />
      <af-table-column label="兑换所需积分" align="left" prop="saleIntegral" />
      <af-table-column
        label="商品图片"
        align="left"
        prop="waresPic"
        v-if="false"
      />
      <af-table-column
        label="商品详情文案"
        align="left"
        prop="waresDetail"
        width="155"
      />
      <af-table-column label="库存" align="left" prop="waresCount" />
      <af-table-column
        label="商品状态"
        align="left"
        prop="waresStatus"
        :formatter="waresStatusFotmat"
      />
      <af-table-column
        label="操作"
        align="left"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="updateSJ(scope.row)"
          >
            {{
              scope.row.waresStatus == 1
                ? "下架"
                : scope.row.waresStatus == 2
                ? "上架"
                : ""
            }}
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDataUpdate(scope.row)"
          >
            修改资料
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleStockUpdate(scope.row)"
          >
            修改库存
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </af-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item
          label="商品图片"
          prop="waresPic"
          :required="operation == 1 || operation == 3"
          v-if="operation == 1 || operation == 3"
        >
          <el-upload
            class="avatar-uploader"
            :action="addressUrl"
            :headers="headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="form.waresPic"
              :src="form.waresPic"
              style="width: 150px; height: 150px"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div class="el-upload__tip" slot="tip">
              点击图片重新上传，图片大小不超过5M
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item
          label="商品名称"
          prop="waresName"
          :required="operation == 1 || operation == 3"
          v-if="operation == 1 || operation == 3"
        >
          <el-input
            type="text"
            maxlength="20"
            show-word-limit
            v-model="form.waresName"
            placeholder="请输入商品名称"
          />
        </el-form-item>

        <el-form-item
          label="油站"
          prop="stationId"
          :required="userLevel == 1 && operation == 3"
          v-if="userLevel == 1 && operation == 3"
        >
          <el-select v-model="form.stationId" placeholder="请选择油站">
            <el-option
              v-for="item in stationList"
              :key="item.stationId"
              :label="item.stationName"
              :value="item.stationId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="优惠券商品"
          prop="isCouponProduct"
          :required="operation == 1 || operation == 3"
          v-if="operation == 1 || operation == 3"
        >
          <el-select
            v-model="form.isCouponProduct"
            clearable
            placeholder="请选择状态"
          >
            <el-option label="不关联" value="0"></el-option>
            <el-option label="关联" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="关联的优惠券"
          prop="issueId"
          :required="form.isCouponProduct == 1"
          v-if="form.isCouponProduct == 1"
        >
          <el-select v-model="form.issueId" clearable placeholder="请选择状态">
            <el-option
              v-for="ele in issueList"
              :key="ele.id"
              :label="ele.issueRemark + ' - ' + ele.id"
              :value="ele.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="商品介绍文案"
          prop="waresDetail"
          :required="operation == 1 || operation == 3"
          v-if="operation == 1 || operation == 3"
        >
          <textarea
            v-model="form.waresDetail"
            placeholder="介绍文案"
            rows="4"
            cols="40"
          ></textarea>
        </el-form-item>
        <el-form-item
          label="兑换所需积分"
          prop="saleIntegral"
          :required="operation == 1 || operation == 3"
          v-if="operation == 1 || operation == 3"
        >
          <el-input-number
            v-model="form.saleIntegral"
            :min="0"
            placeholder="兑换积分"
          />
        </el-form-item>
        <el-form-item
          label="库存"
          prop="waresCount"
          :required="operation == 2 || operation == 3"
          v-if="operation == 2 || operation == 3"
        >
          <el-input-number
            v-model="form.waresCount"
            :min="0"
            placeholder="请输入库存数量"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listWares,
  getWares,
  editInfoWares,
  addWares,
  updateWares,
} from "@/api/integral/wares";
import { getToken } from "@/utils/auth";
import { getStationList } from "@/api/dept";
import { listIssue } from "@/api/coupon";
import { creationList } from "@/api/coupon/creation";

export default {
  name: "Wares",
  data() {
    return {
      // 总条数
      total: 0,
      // 表格数据
      waresList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        waresName: null,
      },
      deptInfo: {},
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // waresName: [
        //   { required: true, message: "请输入商品名称", trigger: "blur" },
        // ],
      },
      headers: { Authorization: "Bearer " + getToken() },
      addressUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      operation: 1, // 1 修改资料 2修改库存 3 添加
      stationList: [],
      issueList: [],
    };
  },
  created() {
    this.getList();
    this.getStationList();
    this.getIssueList();
  },
  methods: {
    getIssueList() {
      creationList({
        status: "1", // 状态为启动
      })
        .then((res) => {
          if (res.code == 200) {
            if (res.rows == null) {
              this.issueList = [];
            } else {
              this.issueList = res.rows;
            }
          } else {
            throw new Error("");
          }
        })
        .catch((err) => {
          this.msgError("亲，拉取领取方式列表失败~");
        });
    },
    // getIssueList() {
    //   listIssue({
    //     // 拉取发放方式
    //     pageNum: 1,
    //     pageSize: 1000,
    //     issueName: null,
    //     issueRemark: null,
    //     status: "1", // 状态为启动
    //   })
    //     .then((res) => {
    //       if (res.code == 200) {
    //         if (res.rows == null) {
    //           this.issueList = [];
    //         } else {
    //           this.issueList = res.rows;
    //           // console.log("yyyyy", this.issueList);
    //         }
    //       } else {
    //         throw new Error("");
    //       }
    //     })
    //     .catch((err) => {
    //       this.msgError("亲，拉取领取方式列表失败~");
    //     });
    // },
    waresStatusFotmat(row, column) {
      if (row.waresStatus === "1") {
        return "已上架";
      } else if (row.waresStatus === "2") {
        return "已下架";
      }
    },

    /** 查询【请填写功能名称】列表 */
    getList() {
      listWares(this.queryParams).then((response) => {
        this.waresList = response.rows;
        this.total = response.total;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    getStationList() {
      if (this.userLevel != "1") {
        return;
      }
      getStationList({
        enterpriseId: this.presentEnterprise.enterpriseId,
      }).then((res) => {
        this.stationList = res.rows;
      });
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.operation = 3;
      this.open = true;
      this.title = "添加商品信息";
    },
    /** 修改资料操作 */
    handleDataUpdate(row) {
      const id = row.id;
      this.operation = 1;
      getWares(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品信息";
      });
    },
    handleStockUpdate(row) {
      const id = row.id;
      this.operation = 2;
      getWares(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改库存信息";
      });
    },
    updateSJ(row) {
      this.reset();
      this.form.id = row.id;
      if (row.waresStatus == 1) {
        this.form.waresStatus = 2;
      } else {
        this.form.waresStatus = 1;
      }
      if (this.form.id != null) {
        editInfoWares(this.form).then((response) => {
          this.msgSuccess("修改成功");
          this.getList();
        });
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.operation == 1 || this.operation == 3) {
            if (this.form.id != null) {
              updateWares(this.form).then((response) => {
                this.msgSuccess("修改成功2");
                this.open = false;
                this.getList();
              });
            } else {
              addWares(this.form).then((response) => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          } else {
            editInfoWares(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.getList();
              this.open = false;
            });
          }
        }
      });
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm("是否确认此商品?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.form = row;
        this.form.waresStatus = 3;
        editInfoWares(this.form).then((response) => {
          this.msgSuccess("删除成功");
          this.getList();
        });
      });
    },
    // 文件上传成功处理++ =
    handleAvatarSuccess(res, file) {
      this.form.waresPic = res.url;
      this.form = { ...this.form };
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === "image/jpeg" || "image/png";
      const isLt2M = file.size / 1024 / 1024 < 5;
      // if (!isJPG) {
      //   this.$message.error("上传头像图片只能是 JPG 格式!");
      // }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 5MB!");
      }
      // return isJPG && isLt2M;
      return isLt2M;
    },
  },
};
</script>
<style scoped>
.point_product {
  padding: 15px;
}
</style>
